import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/services.dart';


enum NetworkState {
    wifi,
    /// 窝蜂数据
    mobile,
    none
}

class NetworkListen {
    static NetworkState currentState = NetworkState.none;
    static Connectivity _connectivity = Connectivity();
    static StreamSubscription<ConnectivityResult> _connectivitySubscription;
    static NetworkListen _networkListen;

    factory NetworkListen() => _getInstance();
    static NetworkListen _getInstance() {
        if (_networkListen == null) {
            _networkListen = NetworkListen._internal();
        }
        return _networkListen;
    }
    NetworkListen._internal() {
        /// 获取当前网络
        getCurrentState();
        /// 监听网络变化
        _connectivitySubscription =
                _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
    }

    // Platform messages are asynchronous, so we initialize in an async method.
    static Future<NetworkState> getCurrentState() async {
        ConnectivityResult result;
        // Platform messages may fail, so we use a try/catch PlatformException.
        try {
            result = await _connectivity.checkConnectivity();
        } on PlatformException catch (e) {
            print(e.toString());
        }
        return _updateConnectionStatus(result);
    }
    /// 更新网络状态
    static Future<NetworkState> _updateConnectionStatus(ConnectivityResult result) async {
        switch (result) {
            case ConnectivityResult.wifi:
                currentState = NetworkState.wifi;
                break;
            case ConnectivityResult.mobile:
                currentState = NetworkState.mobile;
                break;
            case ConnectivityResult.none:
                currentState = NetworkState.none;
                break;
        }
        return currentState;
    }
    /// 取消监听
    cancelListen() {
        _connectivitySubscription.cancel();
    }
}